package org.apache.click.doubleclick.annotationconfig;

import org.scannotation.AnnotationDB;
import org.scannotation.archiveiterator.Filter;
import org.scannotation.archiveiterator.IteratorFactory;
import org.scannotation.archiveiterator.StreamIterator;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class ExtendedAnnotationDB extends AnnotationDB {
    private Filter filter;

    public ExtendedAnnotationDB() {
    }

    public ExtendedAnnotationDB(Filter filter) {
        this.filter = filter;
    }

    @Override
    public void scanArchives(URL... urls) throws IOException {
        for (URL url : urls) {
            Filter filter = new Filter() {
                public boolean accepts(String filename) {
                    if (filename.endsWith(".class")) {
                        if (filename.startsWith("/")) {
                            filename = filename.substring(1);
                        }

                        if (!ignoreScan(filename.replace('/', '.'))) {
                            if (ExtendedAnnotationDB.this.filter != null) {
                                return ExtendedAnnotationDB.this.filter.accepts(filename);
                            } else {
                                return true;
                            }
                        }
                    }
                    return false;
                }
            };

            StreamIterator it = IteratorFactory.create(url, filter);
            InputStream stream;
            while ((stream = it.next()) != null) scanClass(stream);
        }
    }

    private boolean ignoreScan(String intf) {
        for (String ignored : ignoredPackages) {
            if (intf.startsWith(ignored + ".")) {
                return true;
            } else {
                //System.out.println("NOT IGNORING: " + intf);
            }
        }
        return false;
    }
}
